package com.qms.qep.service.impl;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qms.qep.service.IDataAnalysisService;
import com.qms.qep.mapper.ProductionStatisticsMapper;
import com.qms.qep.mapper.InspectionDataMapper;
import com.qms.qep.mapper.NonconformingMapper;
import com.qms.qep.mapper.DefectRecordMapper;
import com.qms.qep.mapper.RepairTaskMapper;
import com.qms.qep.mapper.SpcAnalysisMapper;
import com.qms.qep.mapper.ProcessRecordMapper;
import com.qms.qep.mapper.BatchMapper;
import com.qms.qep.mapper.ProcessMapper;
import com.qms.qep.mapper.ProductMapper;
import com.qms.qep.domain.Batch;
import com.qms.qep.domain.Process;

/**
 * 数据分析Service实现
 * 
 * @author qms
 */
@Service
public class DataAnalysisServiceImpl implements IDataAnalysisService {

    @Autowired
    private ProductionStatisticsMapper productionStatisticsMapper;
    
    @Autowired
    private InspectionDataMapper inspectionDataMapper;
    
    @Autowired
    private NonconformingMapper nonconformingMapper;
    
    @Autowired
    private DefectRecordMapper defectRecordMapper;
    
    @Autowired
    private RepairTaskMapper repairTaskMapper;
    
    @Autowired
    private SpcAnalysisMapper spcAnalysisMapper;
    
    @Autowired
    private ProcessRecordMapper processRecordMapper;
    
    @Autowired
    private BatchMapper batchMapper;
    
    @Autowired
    private ProcessMapper processMapper;
    
    @Autowired
    private ProductMapper productMapper;

    /**
     * 获取合格率统计数据
     */
    @Override
    public Map<String, Object> getQualificationRate(Integer productId, String productName, Integer batchId, String batchNo, Integer processId, String processName, String startDate, String endDate) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查是否提供了名称而非ID
        if (productId == null && productName != null && !productName.isEmpty()) {
            // 根据产品名称查找产品ID
            Map<String, Object> productParams = new HashMap<>();
            productParams.put("name", productName);
            List<Map<String, Object>> products = productMapper.selectProductListToMap(productParams);
            if (products != null && !products.isEmpty()) {
                productId = Integer.valueOf(products.get(0).get("id").toString());
            }
        }
        
        if (batchId == null && batchNo != null && !batchNo.isEmpty()) {
            // 根据批次号查找批次ID
            Batch batch = batchMapper.selectBatchByBatchNo(batchNo);
            if (batch != null) {
                batchId = batch.getId().intValue();
            }
        }
        
        if (processId == null && processName != null && !processName.isEmpty()) {
            // 根据工序名称查找工序ID
            Process process = new Process();
            process.setName(processName);
            List<Process> processes = processMapper.selectProcessList(process);
            if (processes != null && !processes.isEmpty()) {
                processId = processes.get(0).getId().intValue();
            }
        }
        
        // 根据条件查询生产统计数据
        Map<String, Object> params = new HashMap<>();
        params.put("productId", productId);
        params.put("batchId", batchId);
        params.put("processId", processId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        
        // 汇总数据
        Map<String, Object> summary = productionStatisticsMapper.getQualificationRateSummary(params);
        if (summary != null) {
            result.put("summary", summary);
        } else {
            result.put("summary", new HashMap<>());
        }
        
        // 按产品统计
        if (productId == null) {
            List<Map<String, Object>> productStats = productionStatisticsMapper.getQualificationRateByProduct(params);
            result.put("productStats", productStats);
        }
        
        // 按批次统计
        if (batchId == null && productId != null) {
            List<Map<String, Object>> batchStats = productionStatisticsMapper.getQualificationRateByBatch(params);
            result.put("batchStats", batchStats);
        }
        
        // 按工序统计
        if (processId == null) {
            List<Map<String, Object>> processStats = productionStatisticsMapper.getQualificationRateByProcess(params);
            result.put("processStats", processStats);
        }
        
        return result;
    }

    /**
     * 获取合格率趋势数据
     */
    @Override
    public Map<String, Object> getQualificationTrend(Integer productId, String productName, Integer batchId, String batchNo, Integer processId, String processName, String startDate, String endDate, String timeGranularity) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查是否提供了名称而非ID
        if (productId == null && productName != null && !productName.isEmpty()) {
            // 根据产品名称查找产品ID
            Map<String, Object> productParams = new HashMap<>();
            productParams.put("name", productName);
            List<Map<String, Object>> products = productMapper.selectProductListToMap(productParams);
            if (products != null && !products.isEmpty()) {
                productId = Integer.valueOf(products.get(0).get("id").toString());
            }
        }
        
        if (batchId == null && batchNo != null && !batchNo.isEmpty()) {
            // 根据批次号查找批次ID
            Batch batch = batchMapper.selectBatchByBatchNo(batchNo);
            if (batch != null) {
                batchId = batch.getId().intValue();
            }
        }
        
        if (processId == null && processName != null && !processName.isEmpty()) {
            // 根据工序名称查找工序ID
            Process process = new Process();
            process.setName(processName);
            List<Process> processes = processMapper.selectProcessList(process);
            if (processes != null && !processes.isEmpty()) {
                processId = processes.get(0).getId().intValue();
            }
        }
        
        // 设置默认时间粒度为"day"
        if (timeGranularity == null || timeGranularity.isEmpty()) {
            timeGranularity = "day";
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("productId", productId);
        params.put("batchId", batchId);
        params.put("processId", processId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("timeGranularity", timeGranularity);
        
        List<Map<String, Object>> trendData = productionStatisticsMapper.getQualificationRateTrend(params);
        result.put("trend", trendData);
        result.put("timeGranularity", timeGranularity);
        
        return result;
    }

    /**
     * 获取合格率对比数据
     */
    @Override
    public Map<String, Object> getQualificationCompare(String dimension, List<Integer> dimensionIds, String startDate, String endDate) {
        Map<String, Object> result = new HashMap<>();
        
        Map<String, Object> params = new HashMap<>();
        params.put("dimensionIds", dimensionIds);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        
        List<Map<String, Object>> compareData = new ArrayList<>();
        
        if ("product".equals(dimension)) {
            compareData = productionStatisticsMapper.compareQualificationRateByProducts(params);
        } else if ("batch".equals(dimension)) {
            compareData = productionStatisticsMapper.compareQualificationRateByBatches(params);
        } else if ("process".equals(dimension)) {
            compareData = productionStatisticsMapper.compareQualificationRateByProcesses(params);
        }
        
        result.put("dimension", dimension);
        result.put("compareData", compareData);
        
        return result;
    }

    /**
     * 获取缺陷帕累托图数据
     */
    @Override
    public Map<String, Object> getDefectPareto(Integer productId, String productName, Integer batchId, String batchNo, String startDate, String endDate) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查是否提供了名称而非ID
        if (productId == null && productName != null && !productName.isEmpty()) {
            // 根据产品名称查找产品ID
            Map<String, Object> productParams = new HashMap<>();
            productParams.put("name", productName);
            List<Map<String, Object>> products = productMapper.selectProductListToMap(productParams);
            if (products != null && !products.isEmpty()) {
                productId = Integer.valueOf(products.get(0).get("id").toString());
            }
        }
        
        if (batchId == null && batchNo != null && !batchNo.isEmpty()) {
            // 根据批次号查找批次ID
            Batch batch = batchMapper.selectBatchByBatchNo(batchNo);
            if (batch != null) {
                batchId = batch.getId().intValue();
            }
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("productId", productId);
        params.put("batchId", batchId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        
        List<Map<String, Object>> defectStats = defectRecordMapper.getDefectStatistics(params);
        
        if (defectStats != null && !defectStats.isEmpty()) {
            // 计算总缺陷数
            int totalDefects = defectStats.stream()
                    .mapToInt(stat -> Integer.parseInt(stat.get("count").toString()))
                    .sum();
            
            // 按缺陷数量降序排序
            defectStats = defectStats.stream()
                    .sorted((a, b) -> Integer.parseInt(b.get("count").toString()) - Integer.parseInt(a.get("count").toString()))
                    .collect(Collectors.toList());
            
            // 计算累计百分比
            int cumulative = 0;
            for (Map<String, Object> stat : defectStats) {
                int count = Integer.parseInt(stat.get("count").toString());
                cumulative += count;
                double percentage = (double) count / totalDefects * 100;
                double cumulativePercentage = (double) cumulative / totalDefects * 100;
                
                stat.put("percentage", Math.round(percentage * 100) / 100.0); // 保留两位小数
                stat.put("cumulativePercentage", Math.round(cumulativePercentage * 100) / 100.0);
            }
        }
        
        result.put("defectStats", defectStats);
        
        return result;
    }

    /**
     * 获取缺陷分布图数据
     */
    @Override
    public Map<String, Object> getDefectDistribution(Integer productId, String productName, Integer batchId, String batchNo, String startDate, String endDate) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查是否提供了名称而非ID
        if (productId == null && productName != null && !productName.isEmpty()) {
            // 根据产品名称查找产品ID
            Map<String, Object> productParams = new HashMap<>();
            productParams.put("name", productName);
            List<Map<String, Object>> products = productMapper.selectProductListToMap(productParams);
            if (products != null && !products.isEmpty()) {
                productId = Integer.valueOf(products.get(0).get("id").toString());
            }
        }
        
        if (batchId == null && batchNo != null && !batchNo.isEmpty()) {
            // 根据批次号查找批次ID
            Batch batch = batchMapper.selectBatchByBatchNo(batchNo);
            if (batch != null) {
                batchId = batch.getId().intValue();
            }
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("productId", productId);
        params.put("batchId", batchId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        
        // 按位置分布统计
        List<Map<String, Object>> locationDistribution = defectRecordMapper.getDefectLocationDistribution(params);
        result.put("locationDistribution", locationDistribution);
        
        // 按严重程度分布统计
        List<Map<String, Object>> severityDistribution = defectRecordMapper.getDefectSeverityDistribution(params);
        result.put("severityDistribution", severityDistribution);
        
        // 按缺陷类型分布统计
        List<Map<String, Object>> typeDistribution = defectRecordMapper.getDefectTypeDistribution(params);
        result.put("typeDistribution", typeDistribution);
        
        return result;
    }

    /**
     * 获取TOP缺陷分析数据
     */
    @Override
    public Map<String, Object> getDefectTop(Integer productId, String productName, Integer batchId, String batchNo, String startDate, String endDate, Integer limit) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查是否提供了名称而非ID
        if (productId == null && productName != null && !productName.isEmpty()) {
            // 根据产品名称查找产品ID
            Map<String, Object> productParams = new HashMap<>();
            productParams.put("name", productName);
            List<Map<String, Object>> products = productMapper.selectProductListToMap(productParams);
            if (products != null && !products.isEmpty()) {
                productId = Integer.valueOf(products.get(0).get("id").toString());
            }
        }
        
        if (batchId == null && batchNo != null && !batchNo.isEmpty()) {
            // 根据批次号查找批次ID
            Batch batch = batchMapper.selectBatchByBatchNo(batchNo);
            if (batch != null) {
                batchId = batch.getId().intValue();
            }
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("productId", productId);
        params.put("batchId", batchId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("limit", limit);
        
        List<Map<String, Object>> topDefects = defectRecordMapper.getTopDefects(params);
        result.put("topDefects", topDefects);
        
        return result;
    }

    /**
     * 获取维修率统计数据
     */
    @Override
    public Map<String, Object> getRepairRate(Integer productId, String productName, Integer batchId, String batchNo, String startDate, String endDate) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查是否提供了名称而非ID
        if (productId == null && productName != null && !productName.isEmpty()) {
            // 根据产品名称查找产品ID
            Map<String, Object> productParams = new HashMap<>();
            productParams.put("name", productName);
            List<Map<String, Object>> products = productMapper.selectProductListToMap(productParams);
            if (products != null && !products.isEmpty()) {
                productId = Integer.valueOf(products.get(0).get("id").toString());
            }
        }
        
        if (batchId == null && batchNo != null && !batchNo.isEmpty()) {
            // 根据批次号查找批次ID
            Batch batch = batchMapper.selectBatchByBatchNo(batchNo);
            if (batch != null) {
                batchId = batch.getId().intValue();
            }
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("productId", productId);
        params.put("batchId", batchId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        
        // 维修率总体统计
        Map<String, Object> summary = repairTaskMapper.getRepairRateSummary(params);
        result.put("summary", summary);
        
        // 按产品统计维修率
        if (productId == null) {
            List<Map<String, Object>> productRepairRates = repairTaskMapper.getRepairRateByProduct(params);
            result.put("productRepairRates", productRepairRates);
        }
        
        // 按批次统计维修率
        if (batchId == null && productId != null) {
            List<Map<String, Object>> batchRepairRates = repairTaskMapper.getRepairRateByBatch(params);
            result.put("batchRepairRates", batchRepairRates);
        }
        
        // 按缺陷类型统计维修率
        List<Map<String, Object>> defectTypeRepairRates = repairTaskMapper.getRepairRateByDefectType(params);
        result.put("defectTypeRepairRates", defectTypeRepairRates);
        
        return result;
    }

    /**
     * 获取维修成本分析数据
     */
    @Override
    public Map<String, Object> getRepairCost(Integer productId, String productName, Integer batchId, String batchNo, String startDate, String endDate) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查是否提供了名称而非ID
        if (productId == null && productName != null && !productName.isEmpty()) {
            // 根据产品名称查找产品ID
            Map<String, Object> productParams = new HashMap<>();
            productParams.put("name", productName);
            List<Map<String, Object>> products = productMapper.selectProductListToMap(productParams);
            if (products != null && !products.isEmpty()) {
                productId = Integer.valueOf(products.get(0).get("id").toString());
            }
        }
        
        if (batchId == null && batchNo != null && !batchNo.isEmpty()) {
            // 根据批次号查找批次ID
            Batch batch = batchMapper.selectBatchByBatchNo(batchNo);
            if (batch != null) {
                batchId = batch.getId().intValue();
            }
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("productId", productId);
        params.put("batchId", batchId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        
        // 维修成本总体统计
        Map<String, Object> summary = repairTaskMapper.getRepairCostSummary(params);
        result.put("summary", summary);
        
        // 按缺陷类型统计维修成本
        List<Map<String, Object>> defectTypeCosts = repairTaskMapper.getRepairCostByDefectType(params);
        result.put("defectTypeCosts", defectTypeCosts);
        
        // 按月度统计维修成本趋势
        List<Map<String, Object>> monthlyCosts = repairTaskMapper.getRepairCostByMonth(params);
        result.put("monthlyCosts", monthlyCosts);
        
        return result;
    }

    /**
     * 获取维修效果评估数据
     */
    @Override
    public Map<String, Object> getRepairEvaluation(Integer productId, String productName, Integer batchId, String batchNo, String startDate, String endDate) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查是否提供了名称而非ID
        if (productId == null && productName != null && !productName.isEmpty()) {
            // 根据产品名称查找产品ID
            Map<String, Object> productParams = new HashMap<>();
            productParams.put("name", productName);
            List<Map<String, Object>> products = productMapper.selectProductListToMap(productParams);
            if (products != null && !products.isEmpty()) {
                productId = Integer.valueOf(products.get(0).get("id").toString());
            }
        }
        
        if (batchId == null && batchNo != null && !batchNo.isEmpty()) {
            // 根据批次号查找批次ID
            Batch batch = batchMapper.selectBatchByBatchNo(batchNo);
            if (batch != null) {
                batchId = batch.getId().intValue();
            }
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("productId", productId);
        params.put("batchId", batchId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        
        // 维修效果评估总体统计
        Map<String, Object> summary = repairTaskMapper.getRepairEvaluationSummary(params);
        result.put("summary", summary);
        
        // 按缺陷类型统计维修效果
        List<Map<String, Object>> defectTypeEvaluations = repairTaskMapper.getRepairEvaluationByDefectType(params);
        result.put("defectTypeEvaluations", defectTypeEvaluations);
        
        // 维修合格率趋势
        List<Map<String, Object>> qualificationTrend = repairTaskMapper.getRepairQualificationTrend(params);
        result.put("qualificationTrend", qualificationTrend);
        
        return result;
    }

    /**
     * 获取过程能力指数(Cp/Cpk)
     */
    @Override
    public Map<String, Object> getProcessCapability(Integer productId, String productName, Integer batchId, String batchNo, Integer paramId, String paramName) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查是否提供了名称而非ID
        if (productId == null && productName != null && !productName.isEmpty()) {
            // 根据产品名称查找产品ID
            Map<String, Object> productParams = new HashMap<>();
            productParams.put("name", productName);
            List<Map<String, Object>> products = productMapper.selectProductListToMap(productParams);
            if (products != null && !products.isEmpty()) {
                productId = Integer.valueOf(products.get(0).get("id").toString());
            }
        }
        
        if (batchId == null && batchNo != null && !batchNo.isEmpty()) {
            // 根据批次号查找批次ID
            Batch batch = batchMapper.selectBatchByBatchNo(batchNo);
            if (batch != null) {
                batchId = batch.getId().intValue();
            }
        }
        
        // 参数名称转ID的逻辑需要根据实际情况实现
        // 这里仅做简单示例
        if (paramId == null && paramName != null && !paramName.isEmpty()) {
            // 假设有一个获取参数ID的方法
            // paramId = getParamIdByName(paramName);
            // 实际项目中需根据实际情况实现
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("productId", productId);
        params.put("batchId", batchId);
        params.put("paramId", paramId);
        
        // 获取过程能力分析数据
        Map<String, Object> capability = spcAnalysisMapper.getProcessCapability(params);
        result.put("capability", capability);
        
        // 获取能力指数解读
        result.put("capabilityInterpretation", getCapabilityInterpretation(capability));
        
        // 获取测量数据分布
        List<Map<String, Object>> measurementDistribution = spcAnalysisMapper.getMeasurementDistribution(params);
        result.put("measurementDistribution", measurementDistribution);
        
        return result;
    }

    /**
     * 根据能力指数提供解读
     */
    private Map<String, String> getCapabilityInterpretation(Map<String, Object> capability) {
        Map<String, String> interpretation = new HashMap<>();
        
        if (capability != null) {
            Double cp = Double.parseDouble(capability.get("cp").toString());
            Double cpk = Double.parseDouble(capability.get("cpk").toString());
            
            // Cp解读
            if (cp < 1.0) {
                interpretation.put("cp", "过程能力不足，需要改进工艺。");
            } else if (cp >= 1.0 && cp < 1.33) {
                interpretation.put("cp", "过程能力基本达标，但仍有提升空间。");
            } else if (cp >= 1.33 && cp < 1.67) {
                interpretation.put("cp", "过程能力良好。");
            } else {
                interpretation.put("cp", "过程能力优秀。");
            }
            
            // Cpk解读
            if (cpk < 1.0) {
                interpretation.put("cpk", "过程不稳定，可能产生不合格品，需要调整过程中心。");
            } else if (cpk >= 1.0 && cpk < 1.33) {
                interpretation.put("cpk", "过程稳定性一般，偏离设计中心，需优化调整。");
            } else if (cpk >= 1.33 && cpk < 1.67) {
                interpretation.put("cpk", "过程稳定性良好。");
            } else {
                interpretation.put("cpk", "过程非常稳定，中心与目标值吻合度高。");
            }
            
            // 总体评价
            if (cp >= 1.33 && cpk >= 1.33) {
                interpretation.put("overall", "过程能力良好，稳定性高，可持续生产。");
            } else if (cp >= 1.33 && cpk < 1.33) {
                interpretation.put("overall", "过程分散度合适，但中心偏移，需调整过程中心。");
            } else if (cp < 1.33 && cpk < 1.33) {
                interpretation.put("overall", "过程能力和稳定性均不足，需全面优化工艺。");
            }
        } else {
            interpretation.put("overall", "数据不足，无法进行能力分析。");
        }
        
        return interpretation;
    }

    /**
     * 获取控制图数据
     */
    @Override
    public Map<String, Object> getControlChart(Integer productId, String productName, Integer batchId, String batchNo, Integer paramId, String paramName, String chartType) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查是否提供了名称而非ID
        if (productId == null && productName != null && !productName.isEmpty()) {
            // 根据产品名称查找产品ID
            Map<String, Object> productParams = new HashMap<>();
            productParams.put("name", productName);
            List<Map<String, Object>> products = productMapper.selectProductListToMap(productParams);
            if (products != null && !products.isEmpty()) {
                productId = Integer.valueOf(products.get(0).get("id").toString());
            }
        }
        
        if (batchId == null && batchNo != null && !batchNo.isEmpty()) {
            // 根据批次号查找批次ID
            Batch batch = batchMapper.selectBatchByBatchNo(batchNo);
            if (batch != null) {
                batchId = batch.getId().intValue();
            }
        }
        
        // 参数名称转ID的逻辑需要根据实际情况实现
        if (paramId == null && paramName != null && !paramName.isEmpty()) {
            // 假设有一个获取参数ID的方法
            // paramId = getParamIdByName(paramName);
            // 实际项目中需根据实际情况实现
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("productId", productId);
        params.put("batchId", batchId);
        params.put("paramId", paramId);
        
        // 获取控制图参数
        Map<String, Object> chartParams = spcAnalysisMapper.getControlChartParams(params);
        result.put("chartParams", chartParams);
        
        // 获取测量数据
        List<Map<String, Object>> measurements = spcAnalysisMapper.getMeasurements(params);
        result.put("measurements", measurements);
        
        // 根据控制图类型，计算控制限
        if ("xr".equals(chartType)) {
            // X-R控制图
            result.putAll(calculateXRControlLimits(measurements, chartParams));
        } else if ("p".equals(chartType)) {
            // P控制图
            result.putAll(calculatePControlLimits(measurements, chartParams));
        } else {
            // 自定义控制图，可根据需要扩展
            result.put("chartType", "custom");
        }
        
        return result;
    }

    /**
     * 计算X-R控制图的控制限
     */
    private Map<String, Object> calculateXRControlLimits(List<Map<String, Object>> measurements, Map<String, Object> chartParams) {
        Map<String, Object> result = new HashMap<>();
        
        if (measurements != null && !measurements.isEmpty() && chartParams != null) {
            // 计算X图控制限
            double xBar = Double.parseDouble(chartParams.get("avg").toString());
            double rBar = Double.parseDouble(chartParams.get("range").toString());
            
            // A2系数通常根据子组大小查表获得，这里假设为0.577（子组大小为5）
            double a2 = 0.577;
            
            double xUcl = xBar + a2 * rBar; // X图上控制限
            double xLcl = xBar - a2 * rBar; // X图下控制限
            
            // 计算R图控制限
            // D4、D3系数通常根据子组大小查表获得，这里假设D4=2.114，D3=0（子组大小为5）
            double d4 = 2.114;
            double d3 = 0;
            
            double rUcl = d4 * rBar; // R图上控制限
            double rLcl = d3 * rBar; // R图下控制限
            
            Map<String, Object> xChartLimits = new HashMap<>();
            xChartLimits.put("ucl", xUcl);
            xChartLimits.put("cl", xBar);
            xChartLimits.put("lcl", xLcl);
            
            Map<String, Object> rChartLimits = new HashMap<>();
            rChartLimits.put("ucl", rUcl);
            rChartLimits.put("cl", rBar);
            rChartLimits.put("lcl", rLcl);
            
            result.put("xChartLimits", xChartLimits);
            result.put("rChartLimits", rChartLimits);
            result.put("chartType", "xr");
            
            // 为每个测量点添加X值和R值
            for(Map<String, Object> measurement : measurements) {
                double value = Double.parseDouble(measurement.get("value").toString());
                measurement.put("xValue", value);
                measurement.put("rValue", Math.abs(value - xBar));
            }
        }
        
        return result;
    }

    /**
     * 计算P控制图的控制限
     */
    private Map<String, Object> calculatePControlLimits(List<Map<String, Object>> measurements, Map<String, Object> chartParams) {
        Map<String, Object> result = new HashMap<>();
        
        if (measurements != null && !measurements.isEmpty() && chartParams != null) {
            // 计算P图控制限
            double pBar = Double.parseDouble(chartParams.get("defectRate").toString());
            double n = Double.parseDouble(chartParams.get("sampleSize").toString());
            
            double pUcl = pBar + 3 * Math.sqrt(pBar * (1 - pBar) / n); // P图上控制限
            double pLcl = Math.max(0, pBar - 3 * Math.sqrt(pBar * (1 - pBar) / n)); // P图下控制限
            
            Map<String, Object> pChartLimits = new HashMap<>();
            pChartLimits.put("ucl", pUcl);
            pChartLimits.put("cl", pBar);
            pChartLimits.put("lcl", pLcl);
            
            result.put("pChartLimits", pChartLimits);
            result.put("chartType", "p");
            
            // 为每个测量点添加P值
            for(Map<String, Object> measurement : measurements) {
                boolean isInControl = "1".equals(measurement.get("isInControl").toString());
                measurement.put("pValue", isInControl ? 0 : 1);
                measurement.put("npValue", isInControl ? 0 : 1);
                measurement.put("cValue", isInControl ? 0 : 1);
                measurement.put("uValue", isInControl ? 0 : 1);
            }
        }
        
        return result;
    }

    /**
     * 获取趋势分析数据
     */
    @Override
    public Map<String, Object> getSpcTrend(Integer productId, String productName, Integer batchId, String batchNo, Integer paramId, String paramName, String startDate, String endDate) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查是否提供了名称而非ID
        if (productId == null && productName != null && !productName.isEmpty()) {
            // 根据产品名称查找产品ID
            Map<String, Object> productParams = new HashMap<>();
            productParams.put("name", productName);
            List<Map<String, Object>> products = productMapper.selectProductListToMap(productParams);
            if (products != null && !products.isEmpty()) {
                productId = Integer.valueOf(products.get(0).get("id").toString());
            }
        }
        
        if (batchId == null && batchNo != null && !batchNo.isEmpty()) {
            // 根据批次号查找批次ID
            Batch batch = batchMapper.selectBatchByBatchNo(batchNo);
            if (batch != null) {
                batchId = batch.getId().intValue();
            }
        }
        
        // 参数名称转ID的逻辑需要根据实际情况实现
        if (paramId == null && paramName != null && !paramName.isEmpty()) {
            // 假设有一个获取参数ID的方法
            // paramId = getParamIdByName(paramName);
            // 实际项目中需根据实际情况实现
        }
        
        Map<String, Object> params = new HashMap<>();
        params.put("productId", productId);
        params.put("batchId", batchId);
        params.put("paramId", paramId);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        
        // 获取测量参数趋势数据
        List<Map<String, Object>> trendData = spcAnalysisMapper.getParameterTrend(params);
        result.put("trendData", trendData);
        
        // 计算异常点
        List<Map<String, Object>> anomalies = new ArrayList<>();
        if (trendData != null && !trendData.isEmpty()) {
            // 获取标准差和平均值
            double avg = 0;
            double sum = 0;
            for (Map<String, Object> data : trendData) {
                sum += Double.parseDouble(data.get("value").toString());
            }
            avg = sum / trendData.size();
            
            // 计算标准差
            double variance = 0;
            for (Map<String, Object> data : trendData) {
                double value = Double.parseDouble(data.get("value").toString());
                variance += Math.pow(value - avg, 2);
            }
            double stdDev = Math.sqrt(variance / trendData.size());
            
            // 标记超出3个标准差的点为异常点
            for (Map<String, Object> data : trendData) {
                double value = Double.parseDouble(data.get("value").toString());
                if (Math.abs(value - avg) > 3 * stdDev) {
                    Map<String, Object> anomaly = new HashMap<>(data);
                    anomaly.put("deviation", value - avg);
                    anomalies.add(anomaly);
                }
            }
        }
        
        result.put("anomalies", anomalies);
        
        // 进行简单线性回归预测
        if (trendData != null && trendData.size() >= 5) {
            Map<String, Object> prediction = performLinearRegression(trendData);
            result.put("prediction", prediction);
        }
        
        return result;
    }

    /**
     * 进行简单线性回归分析
     */
    private Map<String, Object> performLinearRegression(List<Map<String, Object>> data) {
        Map<String, Object> result = new HashMap<>();
        
        int n = data.size();
        double sumX = 0;
        double sumY = 0;
        double sumXY = 0;
        double sumXX = 0;
        
        for (int i = 0; i < n; i++) {
            double x = i;
            double y = Double.parseDouble(data.get(i).get("value").toString());
            
            sumX += x;
            sumY += y;
            sumXY += x * y;
            sumXX += x * x;
        }
        
        double slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX);
        double intercept = (sumY - slope * sumX) / n;
        
        // 计算预测值
        List<Map<String, Object>> predictedValues = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            Map<String, Object> point = new HashMap<>();
            point.put("x", data.get(i).get("date"));
            point.put("y", intercept + slope * i);
            predictedValues.add(point);
        }
        
        // 预测未来几个点
        for (int i = n; i < n + 3; i++) {
            Map<String, Object> point = new HashMap<>();
            // 假设日期是连续的，这里简单处理
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date lastDate = sdf.parse(data.get(n-1).get("date").toString());
                Date predictDate = new Date(lastDate.getTime() + (i - n + 1) * 24 * 60 * 60 * 1000);
                point.put("x", sdf.format(predictDate));
            } catch (Exception e) {
                point.put("x", "Future" + (i - n + 1));
            }
            point.put("y", intercept + slope * i);
            predictedValues.add(point);
        }
        
        result.put("slope", slope);
        result.put("intercept", intercept);
        result.put("values", predictedValues);
        
        // 趋势判断
        if (Math.abs(slope) < 0.01) {
            result.put("trend", "稳定");
        } else if (slope > 0) {
            result.put("trend", "上升");
        } else {
            result.put("trend", "下降");
        }
        
        return result;
    }

    /**
     * 获取产品生命周期追溯
     */
    @Override
    public Map<String, Object> getProductTrace(Integer productId) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取产品基本信息
        Map<String, Object> productInfo = productMapper.selectProductByIntegerId(productId);
        result.put("product", productInfo);
        
        // 获取产品所有批次
        List<Map<String, Object>> batches = batchMapper.getBatchesByProductId(productId);
        // 处理日期时间类型
        processDates(batches, "createTime", "updateTime");
        result.put("batches", batches);
        
        // 获取产品生产过程记录
        List<Map<String, Object>> processRecords = processRecordMapper.getProductProcessRecords(productId);
        // 处理日期时间类型
        processDates(processRecords, "operationTime", "createTime");
        result.put("processes", processRecords);
        
        // 获取产品检验记录
        List<Map<String, Object>> inspectionRecords = inspectionDataMapper.getProductInspectionRecords(productId);
        // 处理日期时间类型
        processDates(inspectionRecords, "inspectionTime", "createTime");
        result.put("inspections", inspectionRecords);
        
        // 获取产品缺陷记录
        List<Map<String, Object>> defectRecords = defectRecordMapper.getProductDefectRecords(productId);
        // 处理日期时间类型
        processDates(defectRecords, "createTime");
        result.put("defects", defectRecords);
        
        // 获取产品维修记录
        List<Map<String, Object>> repairRecords = repairTaskMapper.getProductRepairRecords(productId);
        // 处理日期时间类型
        processDates(repairRecords, "startTime", "endTime", "createTime");
        result.put("repairs", repairRecords);
        
        // 生成产品生命周期流程
        List<Map<String, Object>> lifecycle = createProductLifecycle(
            processRecords, inspectionRecords, defectRecords, repairRecords);
        result.put("lifecycle", lifecycle);
        
        return result;
    }
    
    /**
     * 处理Map列表中的日期时间类型字段，转换为字符串
     * @param dataList 数据列表
     * @param dateFields 需要处理的日期字段名
     */
    private void processDates(List<Map<String, Object>> dataList, String... dateFields) {
        if (dataList == null || dataList.isEmpty() || dateFields == null || dateFields.length == 0) {
            return;
        }
        
        for (Map<String, Object> item : dataList) {
            for (String field : dateFields) {
                Object dateObj = item.get(field);
                if (dateObj instanceof java.time.LocalDateTime) {
                    // 替换LocalDateTime中的T为空格，使其更易读
                    String dateStr = dateObj.toString().replace('T', ' ');
                    item.put(field, dateStr);
                }
            }
        }
    }

    /**
     * 创建模拟批次数据
     */
    private Map<String, Object> createMockBatch(String batchNo, Integer productId) {
        Map<String, Object> batch = new HashMap<>();
        batch.put("batchNo", batchNo);
        batch.put("productId", productId);
        batch.put("startTime", "2025-04-01");
        batch.put("endTime", "2025-04-15");
        batch.put("status", "completed");
        return batch;
    }
    
    /**
     * 创建模拟工序数据
     */
    private Map<String, Object> createMockProcess(String processCode, String processName, String result) {
        Map<String, Object> process = new HashMap<>();
        process.put("processCode", processCode);
        process.put("processName", processName);
        process.put("operationTime", "2025-04-05");
        process.put("operator", "张三");
        process.put("result", result);
        return process;
    }
    
    /**
     * 创建模拟检验数据
     */
    private Map<String, Object> createMockInspection(String inspectionNo, String inspectionType, String result) {
        Map<String, Object> inspection = new HashMap<>();
        inspection.put("inspectionNo", inspectionNo);
        inspection.put("inspectionType", inspectionType);
        inspection.put("inspectionTime", "2025-04-07");
        inspection.put("inspector", "李四");
        inspection.put("result", result);
        return inspection;
    }

    /**
     * 创建产品生命周期时间线
     */
    private List<Map<String, Object>> createProductLifecycle(
            List<Map<String, Object>> processRecords, 
            List<Map<String, Object>> inspectionRecords,
            List<Map<String, Object>> defectRecords,
            List<Map<String, Object>> repairRecords) {
        
        List<Map<String, Object>> timeline = new ArrayList<>();
        
        // 添加工序记录到时间线
        if (processRecords != null) {
            for (Map<String, Object> record : processRecords) {
                Map<String, Object> event = new HashMap<>();
                // 确保时间戳是字符串类型
                Object timeObj = record.get("operationTime");
                String timestamp;
                if (timeObj instanceof java.time.LocalDateTime) {
                    timestamp = timeObj.toString().replace('T', ' ');
                } else {
                    timestamp = timeObj != null ? timeObj.toString() : "";
                }
                event.put("timestamp", timestamp);
                event.put("type", "process");
                event.put("title", "工序: " + record.get("processName"));
                event.put("description", "操作人: " + record.get("operator") + ", 结果: " + record.get("result"));
                event.put("operator", record.get("operator"));
                timeline.add(event);
            }
        }
        
        // 添加检验记录到时间线
        if (inspectionRecords != null) {
            for (Map<String, Object> record : inspectionRecords) {
                Map<String, Object> event = new HashMap<>();
                // 确保时间戳是字符串类型
                Object timeObj = record.get("inspectionTime");
                String timestamp;
                if (timeObj instanceof java.time.LocalDateTime) {
                    timestamp = timeObj.toString().replace('T', ' ');
                } else {
                    timestamp = timeObj != null ? timeObj.toString() : "";
                }
                event.put("timestamp", timestamp);
                event.put("type", "inspection");
                event.put("title", "检验: " + record.get("inspectionType"));
                event.put("description", "检验员: " + record.get("inspector") + ", 结果: " + record.get("result"));
                event.put("operator", record.get("inspector"));
                timeline.add(event);
            }
        }
        
        // 按时间排序
        timeline.sort((a, b) -> ((String)a.get("timestamp")).compareTo((String)b.get("timestamp")));
        
        return timeline;
    }

    /**
     * 获取批次追溯数据
     */
    @Override
    public Map<String, Object> getBatchTrace(Integer batchId) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取批次基本信息
        Batch batchInfo = batchMapper.selectBatchById(batchId.longValue());
        Map<String, Object> batchMap = new HashMap<>();
        if (batchInfo != null) {
            batchMap.put("batchId", batchInfo.getId());
            batchMap.put("batchNo", batchInfo.getBatchNo());
            batchMap.put("productId", batchInfo.getProductId());
            batchMap.put("productName", batchInfo.getProductName());
            batchMap.put("status", batchInfo.getStatus());
            batchMap.put("quantity", batchInfo.getQuantity());
            batchMap.put("createTime", batchInfo.getCreateTime());
        }
        result.put("batch", batchMap);
        
        // 获取批次流转记录
        List<Map<String, Object>> processRecords = processRecordMapper.getBatchProcessRecords(batchId);
        result.put("processes", processRecords);
        
        // 获取工序流转统计
        Map<String, Object> params = new HashMap<>();
        params.put("batchId", batchId);
        List<Map<String, Object>> processStats = processRecordMapper.getBatchProcessStats(params);
        result.put("processStats", processStats);
        
        // 获取批次检验记录
        List<Map<String, Object>> inspectionRecords = inspectionDataMapper.getBatchInspectionRecords(batchId);
        result.put("inspections", inspectionRecords);
        
        // 获取批次缺陷记录
        List<Map<String, Object>> defectRecords = defectRecordMapper.getBatchDefectRecords(batchId);
        result.put("defects", defectRecords);
        
        // 获取批次维修记录
        List<Map<String, Object>> repairRecords = repairTaskMapper.getBatchRepairRecords(batchId);
        result.put("repairs", repairRecords);
        
        return result;
    }
    
    /**
     * 获取缺陷追溯数据
     */
    @Override
    public Map<String, Object> getDefectTrace(Integer defectId) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取缺陷基本信息
        Map<String, Object> defectInfo = defectRecordMapper.selectDefectRecordByIdToMap(defectId);
        if (defectInfo == null) {
            return result;
        }
        result.put("defect", defectInfo);
        
        // 获取相关不合格品信息
        List<Map<String, Object>> nonconformingRecords = nonconformingMapper.getNonconformingRecordsByDefectId(defectId);
        result.put("nonconforming", nonconformingRecords);
        
        // 获取维修记录
        List<Map<String, Object>> repairRecords = repairTaskMapper.getRepairRecordsByDefectId(defectId);
        result.put("repairs", repairRecords);
        
        // 查找同类型缺陷 - 使用defectType而不是defectTypeId
        String defectType = (String) defectInfo.get("defectType");
        if (defectType != null && !defectType.isEmpty()) {
            // 构建查询参数
            Map<String, Object> params = new HashMap<>();
            params.put("defectType", defectType);
            
            // 获取同类型缺陷统计信息
            List<Map<String, Object>> similarDefectStats = defectRecordMapper.getSimilarDefectStatistics(params);
            result.put("similarDefectStats", similarDefectStats);
            
            // 获取同类型缺陷（排除当前缺陷）
            Integer defectRecordId = (Integer) defectInfo.get("id");
            if (defectRecordId != null) {
                List<Map<String, Object>> similarDefects = defectRecordMapper.getSimilarDefects(null, defectRecordId);
                result.put("similarDefects", similarDefects);
            }
        }
        
        return result;
    }

    /**
     * 根据产品名称获取产品生命周期追溯
     */
    @Override
    public Map<String, Object> getProductTraceByName(String productName) {
        if (productName == null || productName.isEmpty()) {
            return new HashMap<>();
        }
        
        // 根据产品名称查找产品ID
        Map<String, Object> productParams = new HashMap<>();
        productParams.put("name", productName);
        List<Map<String, Object>> products = productMapper.selectProductListToMap(productParams);
        
        if (products == null || products.isEmpty()) {
            return new HashMap<>();
        }
        
        Integer productId = Integer.valueOf(products.get(0).get("id").toString());
        return getProductTrace(productId);
    }
    
    /**
     * 根据批次号获取批次追溯数据
     */
    @Override
    public Map<String, Object> getBatchTraceByNo(String batchNo) {
        if (batchNo == null || batchNo.isEmpty()) {
            return new HashMap<>();
        }
        
        // 根据批次号查找批次ID
        Batch batch = batchMapper.selectBatchByBatchNo(batchNo);
        
        if (batch == null) {
            return new HashMap<>();
        }
        
        return getBatchTrace(batch.getId().intValue());
    }
    
    /**
     * 根据缺陷名称获取缺陷追溯数据
     */
    @Override
    public Map<String, Object> getDefectTraceByName(String defectName) {
        if (defectName == null || defectName.isEmpty()) {
            return new HashMap<>();
        }
        
        // 根据缺陷名称查找缺陷记录
        Map<String, Object> defectRecord = defectRecordMapper.getDefectByName(defectName);
        
        if (defectRecord == null || defectRecord.isEmpty()) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "未找到名称为 '" + defectName + "' 的缺陷记录");
            return result;
        }
        
        // 获取缺陷ID
        Integer defectId = null;
        if (defectRecord.containsKey("id")) {
            defectId = Integer.valueOf(defectRecord.get("id").toString());
        }
        
        // 使用缺陷ID获取完整的缺陷追溯数据
        if (defectId != null) {
            return getDefectTrace(defectId);
        } else {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "缺陷记录缺少ID信息，无法获取追溯数据");
            return result;
        }
    }
    
    /**
     * 获取所有缺陷名称列表，用于下拉框选择
     */
    @Override
    public List<Map<String, Object>> getDefectNameList() {
        // 调用defectRecordMapper获取所有缺陷名称列表
        List<Map<String, Object>> defectNames = defectRecordMapper.getAllDefectNames();
        
        // 如果Mapper中没有直接获取缺陷名称的方法，可以先获取所有缺陷然后提取名称
        if (defectNames == null) {
            defectNames = new ArrayList<>();
            List<Map<String, Object>> allDefects = defectRecordMapper.getAllDefects();
            
            if (allDefects != null) {
                // 提取所有唯一的缺陷名称
                Map<String, Object> uniqueNames = new HashMap<>();
                for (Map<String, Object> defect : allDefects) {
                    if (defect.containsKey("defectName") && defect.get("defectName") != null) {
                        String name = defect.get("defectName").toString();
                        uniqueNames.put(name, name);
                    }
                }
                
                // 转换为列表形式
                for (String name : uniqueNames.keySet()) {
                    Map<String, Object> nameMap = new HashMap<>();
                    nameMap.put("name", name);
                    nameMap.put("value", name);
                    defectNames.add(nameMap);
                }
            }
        }
        
        return defectNames;
    }
} 